package com.xyz.keshe;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.xyz.keshe.adapter.NewsAdapter;
import com.xyz.keshe.dao.NewsDao;
import com.xyz.keshe.model.News;

import java.util.List;

public class SearchResultActivity extends AppCompatActivity {

    private TextView tvKeyword;
    private ListView lvSearchResult;
    private Button btnBack;
    private TextView tvNoData;

    private NewsDao newsDao;
    private String keyword;
    private List<News> newsList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result);

        // 初始化视图
        tvKeyword = findViewById(R.id.tv_keyword);
        lvSearchResult = findViewById(R.id.lv_search_result);
        btnBack = findViewById(R.id.btn_back);
        tvNoData = findViewById(R.id.tv_no_data);

        // 初始化DAO
        newsDao = new NewsDao(this);

        // 获取搜索关键词
        Intent intent = getIntent();
        keyword = intent.getStringExtra("keyword");

        // 设置关键词显示
        tvKeyword.setText("搜索：\"" + keyword + "\"的结果");

        // 获取搜索结果
        newsList = newsDao.searchNews(keyword);
        NewsAdapter newsAdapter = new NewsAdapter(this, newsList);
        lvSearchResult.setAdapter(newsAdapter);

        // 设置新闻点击事件
        lvSearchResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                News news = (News) parent.getItemAtPosition(position);
                // 跳转到新闻详情页
                Intent newsIntent = new Intent(SearchResultActivity.this, NewsDetailActivity.class);
                newsIntent.putExtra("news_id", news.getId());
                startActivity(newsIntent);
            }
        });

        // 设置返回按钮点击事件
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 显示或隐藏无数据提示
        if (newsList.isEmpty()) {
            tvNoData.setVisibility(View.VISIBLE);
            lvSearchResult.setVisibility(View.GONE);
        } else {
            tvNoData.setVisibility(View.GONE);
            lvSearchResult.setVisibility(View.VISIBLE);
        }
    }
} 